package com.struggle.controller.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @className RabbitConfig
 * @Description Rabbit配置类：生产者消息发送确认
 * @Author liuwj3
 * @Date 2019/10/12 0012 下午 5:11
 **/
@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);

        // 设置开启Mandatory，才能触发ReturnCallback回调函数，无论消息发送结果如何都要强制调用回调函数
        rabbitTemplate.setMandatory(true);
        // 确认消息是否到达broker服务器，也就是只确认是否正确到达exchange中即可，只要正确的到达exchange中，broker即可确认该消息返回给客户端ack
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息确认成功");
            } else {
                // 处理丢失的消息
                // ...
                System.out.println("消息确认失败");
            }
            System.out.println("ConfirmCallback:     " + "相关数据：" + correlationData);
            System.out.println("ConfirmCallback:     " + "消息确认情况：" + ack);
            System.out.println("ConfirmCallback:     " + "原因：" + cause);
        });

        // 确认消息已发送到队列：启动消息失败返回，比如路由不到队列时触发回调
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("ReturnCallback:     "+"消息："+message);
            System.out.println("ReturnCallback:     "+"回应码："+replyCode);
            System.out.println("ReturnCallback:     "+"回应信息："+replyText);
            System.out.println("ReturnCallback:     "+"交换机："+exchange);
            System.out.println("ReturnCallback:     "+"路由键："+routingKey);
        });
        return rabbitTemplate;
    }
}

